// const promise = new Promise((resolve, reject) => {
//     resolve('success1'); // promise  pending -> fullfiled?
//     reject('error');
//     resolve('success2');
// })

// promise
//     .then(res => {
//         console.log("then:", res);
//     })
//     .catch(err => {
//         console.log("catch:", err);
//     })


class MyPromise {
    constructor(executor) {
        this.status = 'pending'
        this.value = null
        this.onFulfilledCallbacks = [] // 保存成功的回调
        this.onRejectedCallbacks = [] // 保存失败的回调

        try {
            executor(this.resolve.bind(this), this.reject.bind(this))
        } catch (error) {
            this.reject(error)
        }

    }

    resolve(value) {
        if (this.status !== 'pending') return
        this.status = 'fulfilled'
        this.value = value

        // 调用then里面的回调
        while (this.onFulfilledCallbacks.length) {
            this.onFulfilledCallbacks.shift()(this.value)
        }
    }

    reject(reason) {
        if (this.status !== 'pending') return
        this.status = 'rejected'
        this.value = reason
    }

    then(onFulfilled, onRejected) {
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : val => val
        onRejected = typeof onRejected === 'function' ? onRejected : val => { throw val }
        // onFulfilled()
        var thenPromise = new MyPromise((resolve, reject) => {
            const resolvePromise = cb => {
                setTimeout(()=>{
                    try {
                        const x = cb(this.value)
                        if (x === thenPromise) {
                            throw new Error('不能返回自身...')
                        }
                        if (x instanceof MyPromise) {
                            x.then(resolve, reject)
                        } else {
                            resolve(x)
                        }
                    } catch (error) {
                        reject(error)
                        throw new Error(error)
                    }
                },1000)
            }

            if (this.status === 'fulfilled') {
                resolvePromise(onFulfilled)
            } else if (this.status === 'rejected') {
                resolvePromise(onRejected)
            } else if (this.status === 'pending') {
                this.onFulfilledCallbacks.push(resolvePromise.bind(this, onFulfilled))
                this.onRejectedCallbacks.push(resolvePromise.bind(this.onRejected))
            }
            // onRejected()
        })
        return thenPromise
    }
}

let p1 = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve(100)
    }, 1000)
    // resolve(100)
    // resolve('ok')
    // reject('err')
    // throw ('代码出错了')
})
p1.then(
    res => 2*res,
    err => console.log(err)
).then(
    res => console.log(res),
    err => console.log(err)
)
console.log(123);